from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.common.exceptions import InvalidArgumentException, WebDriverException, NoSuchElementException, \
    TimeoutException
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time


class Base:
    # 初始化打开浏览器
    def __init__(self, driver):
        # 打开浏览器
        if driver == 'chrome':
            self.driver = webdriver.Chrome()
        elif driver == 'firefox':
            self.driver = webdriver.Firefox()
        elif driver == 'edge':
            self.driver = webdriver.Edge()
        else:
            print('该浏览器不适配')

        # 最大化
        self.driver.maximize_window()

    # 请求网址
    def get(self, url):
        # 请求网址
        try:
            self.driver.get(url)
            # 设置隐式等待
            self.driver.implicitly_wait(10)
        except (InvalidArgumentException, WebDriverException):
            print('输入的网址不正确')

    # 获取标签定位
    def find_element(self, locator, outtime=10, poll_frequency=0.5):
        try:
            # 显示等待获取标签定位
            return WebDriverWait(self.driver, outtime, poll_frequency).until(EC.presence_of_element_located(locator))
            # 正常获取标签定位 *元组 == 拆分元组
            # return self.driver.find_element(*locator) # 原始方法获取标签定位
        # except NoSuchElementException: # 原始方法获取标签定位
        except TimeoutException:
            print('元素定位失败')

    # 发送信息方法
    def send_key(self, locator, info):
        s1 = self.find_element(locator)
        if s1 is None:
            print('元素定位失败')
        else:
            s1.send_keys(info)

    # 点击方法
    def click(self, locator):
        # 对象赋值
        element = self.find_element(locator)
        if element is None:
            print('元素定位失败')
        else:
            # 对象点击
            element.click()

    # 获取属性
    def get_attribute(self, locator, value):
        element = self.find_element(locator)
        if element is None:
            print('元素定位失败')
        else:
            # return print(element.get_attribute(value)) if element.get_attribute(value) else print('输入的值有误')
            return element.get_attribute(value) if element.get_attribute(value) else print('输入的值有误')

    # 返回方法
    def back(self):
        self.driver.back()

    # 前进方法
    def forward(self):
        self.driver.forward()

    # 刷新方法
    def refresh(self):
        self.driver.refresh()

    # 关闭浏览器
    def quit(self):
        self.driver.quit()


if __name__ == '__main__':
    b1 = Base('chrome')
    b1.driver.get('https://www.baidu.com')
    b1.find_element(('id', 'kw'))
    # b1.get_attribute(('id', 'kw'), 'outerHTML')
    time.sleep(2)
    b1.send_key((By.ID, 'kw'), 'python')
    time.sleep(2)
    b1.click((By.ID, 'su'))
    time.sleep(2)
    b1.back()
    time.sleep(2)
    b1.forward()
    time.sleep(2)
    b1.refresh()
    time.sleep(2)
    b1.quit()
